<template>
	<div id="map">
		<div id="header">
			<div id="r-result">
				<div id="chufa">
					<div class="div_input">
						<span>出发地:</span>
						<input type="search" id="suggestId1" size="20" style="width:250px;" v-model="searchText1" ref="input_search1" />
						<button @click="dingwei" id="dingwei">
							<img src="../assets/dingwei.png" class="dingwei-img">
						</button>
					</div>
					<div id="searchResultPanel1" style="border:1px solid #C0C0C0;width:150px;height:auto;display: none; ">

					</div>
				</div>
				<div id="mudi">
					<div class="div_input">
						<span>目的地:</span><input type="search" id="suggestId" size="20" value="" style="width:150px;" v-model="searchText"
						 ref="input_search" />
					</div>
					<div id="searchResultPanel" style="border:1px solid #C0C0C0;width:150px;height:auto;display: none; ">
					</div>

				</div>
				<div v-if="user.car != null">
					<mt-button type="primary" id='daohang' ref='daohang' value="导航" class="btn-class" @click="run(1)" v-if="!this.flag">导航</mt-button>
					<mt-button type="danger" id='quxiao' ref='quxiao' value="取消" class="btn-class" @click="run(2)" v-else>取消</mt-button>

				</div>

			</div>
		</div>
		<div class="div_map">
			
			<div id="allmap" ref="allmap"></div>

		</div>

	</div>
</template>

<script>
	import BMap from 'BMap'

	export default {

		data() {
			return {
				searchText: '', //目的地
				searchText1: '', //出发地
				frist: true,
				searchReuslt: '',
				nowLoction: '',
				lushu: '',
				mycaiId: '',
				arrPois: [],
				flag: false, //是否正在导航
				infoFlag: false, //车辆信息是否显示				
				dingweiLoc: '', //定位的地点
				searchFlag: false, //查询中
				user: '',
				nowLoc: {
					lon: '',
					lat: ''
				},
				loc: '',
				point: null
			}

		},
		computed: {
			UserCar() {
				return this.$store.state.car
			}
		},
		watch: {
			arrPois() {
				this.daohang();
			},
			searchText(val1, val2) {
				if (val1 == '') {
					this.arrPois.splice(1, 1);
				}
				this.search('suggestId', 0, "searchResultPanel")
			},
			searchText1(val) {
				if (this.dingweiLoc == val) {
					return;
				}
				if (val == '') {
					this.arrPois.splice(0, 1);
				}

				this.search('suggestId1', 1, "searchResultPanel1")
			},
			UserCar: function(val) {
				console.log(val)
				console.log(this.nowLoc)
				console.log(this.nowLoc.lat + '---' + this.nowLoc.lon)
				
				this.nowLoc.lat = val.cur_loc_lat;
				this.nowLoc.lon = val.cur_loc_lon;
				this.point = new BMap.Point(this.nowLoc.lon, this.nowLoc.lat)
				
				if (this.point != null) {
					let point = this.point
					console.log(point)
					map.centerAndZoom(point, 15);
					let marker = new BMap.Marker(point);
					marker.disableMassClear();
					map.addOverlay(new BMap.Marker(point));
					this.getLocation(point);
				} else {
					console.log('dingwei')
					this.dingwei();
				}
			}


		},
		beforeDestroy() {
			this.lushu = null;
		},
		created() {
			this.user = this.$store.state.user[0];
		},
		mounted() {
			this.map()
		},
		methods: {
			/* 地图初始化*/
			map() {
				var map = new BMap.Map(this.$refs.allmap); // 创建Map实例
				window.map = map //将map变量存储在全局

				map.setCurrentCity("北京"); // 设置地图显示的城市 此项是必须设置的
				map.enableScrollWheelZoom(true); //开启鼠标滚轮缩放

				// 添加带有定位的导航控件
				var navigationControl = new BMap.NavigationControl({
					// 靠左上角位置
					anchor: BMAP_ANCHOR_TOP_LEFT,
					// LARGE类型
					type: BMAP_NAVIGATION_CONTROL_LARGE,

				});
				map.addControl(navigationControl);
			},

			/* 导航小车动*/
			run(val) {
				if (val == 1) {

					if (this.lushu) {
						let _that = this
						this.$refs.input_search.disabled = 'disabled';
						this.$refs.input_search1.disabled = 'disabled';
						if (this.flag) {

							console.log(this.nowLoction.lat + '-----' + this.nowLoction.lng);

						} else {
							this.lushu.start();
							this.flag = true;
							var i = document.getElementsByTagName('span');

							for (var y of i) {
								if (y.className == 'BMap_Marker BMap_noprint') {
									y.addEventListener('click', () => {
										if (this.infoFlag == false) {
											this.lushu.showInfoWindow()
										} else {
											this.lushu.hideInfoWindow()
										}
										this.infoFlag = !this.infoFlag;

									})
								}
							}
						}

					} else {
						return
					}
				} else {
					this.arrPois.splice(0, 2);
					this.$refs.input_search.disabled = '';
					this.$refs.input_search1.disabled = '';
					this.searchText = '';
					this.searchText1 = '';
					this.flag = false;
					this.lushu.stop();
					map.clearOverlays();
				}


			},
			daohang() {
				if (this.arrPois.length != 2) {
					return;
				}
				// 实例化一个驾车导航用来生成路线

				let drv = new BMap.DrivingRoute("北京", {
					onSearchComplete: (res) => {
						if (drv.getStatus() == BMAP_STATUS_SUCCESS) {
							let plan = res.getPlan(0);
							let arrPois = [];
							for (let j = 0; j < plan.getNumRoutes(); j++) {
								let route = plan.getRoute(j);
								arrPois = arrPois.concat(route.getPath());
							}
							map.addOverlay(new BMap.Polyline(arrPois, {
								strokeColor: "green",
								strokeWeight: 5,
							}));
							map.setViewport(arrPois);

							this.lushu = new BMapLib.LuShu(map, arrPois, {
								defaultContent: `<p>车辆类型:小轿车</p><p>车牌号:粤A12345</p>`, //"从天安门到百度大厦"
								autoView: true, //是否开启自动视野调整，如果开启那么路书在运动过程中会根据视野自动调整
								icon: new BMap.Icon('http://lbsyun.baidu.com/jsdemo/img/car.png', new BMap.Size(52, 26), {
									anchor: new BMap.Size(27, 13)
								}),
								speed: 40,
								enableRotation: true, //是否设置marker随着道路的走向进行旋转
								landmarkPois: [],
							});


						}

					}
				});

				drv.search(this.arrPois[0], this.arrPois[1]);

				this.chongxie()

			},
			chongxie() {
				var _that = this;
				BMapLib.LuShu.prototype._move = function(initPos, targetPos, effect) {
					var pointsArr = [initPos, targetPos]; //点数组
					var me = this,
						//当前的帧数
						currentCount = 0,
						//步长，米/秒
						timer = 10,
						step = this._opts.speed / (1000 / timer),
						//初始坐标
						init_pos = this._projection.lngLatToPoint(initPos),
						//获取结束点的(x,y)坐标
						target_pos = this._projection.lngLatToPoint(targetPos),
						//总的步长
						count = Math.round(me._getDistance(init_pos, target_pos) / step);

					this._map.addOverlay(new BMap.Polyline(pointsArr, {
						strokeColor: "red",
						strokeWeight: 6,
						strokeOpacity: 0.5
					})); // 画线 

					// 			获取当前的位置
					// 			console.log(pointsArr[0]);
					_that.nowLoction = pointsArr[0];
					//如果小于1直接移动到下一点

					if (count < 1) {
						me._moveNext(++me.i);
						return;
					}
					//两点之间匀速移动
					me._intervalFlag = setInterval(function() {
						//两点之间当前帧数大于总帧数的时候，则说明已经完成移动
						if (currentCount >= count) {
							clearInterval(me._intervalFlag);
							//移动的点已经超过总的长度
							if (me.i > me._path.length) {
								return;
							}
							//运行下一个点
							me._moveNext(++me.i);
						} else {
							currentCount++;
							var x = effect(init_pos.x, target_pos.x, currentCount, count),
								y = effect(init_pos.y, target_pos.y, currentCount, count),
								pos = me._projection.pointToLngLat(new BMap.Pixel(x, y));
							//设置marker
							if (currentCount == 1) {
								var proPos = null;
								if (me.i - 1 >= 0) {
									proPos = me._path[me.i - 1];
								}
								if (me._opts.enableRotation == true) {
									me.setRotation(proPos, initPos, targetPos);
								}
								if (me._opts.autoView) {
									if (!me._map.getBounds().containsPoint(pos)) {
										me._map.setCenter(pos);
									}
								}
							}
							//正在移动

							me._marker.setPosition(pos);
							//设置自定义overlay的位置
							me._setInfoWin(pos);

						}
					}, timer);
				}
			},
			getLocation(point) { // 地址解析
				let geoc = new BMap.Geocoder();
				geoc.getLocation(point, (result) => {
					let addComp = result.addressComponents;
					this.loc = addComp.province + ", " + addComp.city + ", " + addComp.district + ", " + addComp.street + ", " +
						addComp.streetNumber;
					this.dingweiLoc = this.loc;
					this.searchText1 = this.loc;
					this.$refs.input_search1.readOnly = true

				})

			},
			dingwei() {
				/* 正在导航时不能点击定位*/
				if (this.flag == true) {
					return;
				}
				/* 将设置为不可清除的覆盖物 , 取消设置*/
				var allOverlay = map.getOverlays();
				for (var i = 0; i < allOverlay.length; i++) {
					allOverlay[i].enableMassClear();
				}
				map.clearOverlays();


				var _that = this;

				var geolocation = new BMap.Geolocation();
				geolocation.enableSDKLocation();
				geolocation.getCurrentPosition(function(r) {
					if (this.getStatus() == BMAP_STATUS_SUCCESS) {
						var p0 = r.point.lng;
						var p1 = r.point.lat;
						// var checksum = makerArry[i].checksum;
						var point = new BMap.Point(p0, p1); //118.230272,33.482474

						_that.arrPois.splice(0, 1, point);

						var address = '';
						address += r.address.province;
						address += r.address.city;
						address += r.address.district;
						address += r.address.street;
						address += r.address.street_number;

						_that.searchText1 = address;
						_that.dingweiLoc = address;
						let marker = new BMap.Marker(r.point);
						marker.disableMassClear();
						map.addOverlay(new BMap.Marker(r.point));
						map.centerAndZoom(r.point, 15);
					} else {
						alert('failed' + this.getStatus());
					}
				});
				this.frist = false
			},

			search(id, sure, searchResultPanel) { // sure 确定  1出发地 还是 0目的地 
				console.log(this.searchFlag)
				if (this.searchFlag == true) {
					return;
				}

				function G(id) {
					return document.getElementById(id);
				}


				var ac = new BMap.Autocomplete( //建立一个自动完成的对象
					{
						"input": id,
						"location": map,

					});
				ac.addEventListener("onhighlight", e => { //鼠标放在下拉列表上的事件
					this.searchFlag = true;
					var str = "";
					var _value = e.fromitem.value;
					var value = "";
					if (e.fromitem.index > -1) {
						value = _value.province + _value.city + _value.district + _value.street + _value.business;
					}
					str = "FromItem<br />index = " + e.fromitem.index + "<br />value = " + value;

					value = "";
					if (e.toitem.index > -1) {
						_value = e.toitem.value;
						value = _value.province + _value.city + _value.district + _value.street + _value.business;
					}
					str += "<br />ToItem<br />index = " + e.toitem.index + "<br />value = " + value;

					if (sure == 0) { //目的地
						this.searchText = value

					} else if (sure == 1) { //出发地
						this.searchText1 = value;

					}
					G(searchResultPanel).innerHTML = str;

				});

				var myValue;
				ac.addEventListener("onconfirm", e => { //鼠标点击下拉列表后的事件
					var _value = e.item.value;
					myValue = _value.province + _value.city + _value.district + _value.street + _value.business;
					G(searchResultPanel).innerHTML = "onconfirm<br />index = " + e.item.index + "<br />myValue = " + myValue;

					setPlace(this, sure);
				});

				function setPlace(_that, sure) {
					map.clearOverlays(); //清除地图上所有覆盖物
					let myGeo = new BMap.Geocoder();

					function myFun() {
						let pp = local.getResults().getPoi(0).point; //获取第一个智能搜索的结果
						let rs = local.getResults().getPoi(0);
						if (sure == 0) { //目的地

							_that.searchReuslt = rs;
							let p0 = rs.point.lng;
							let p1 = rs.point.lat;
							// var checksum = makerArry[i].checksum;
							let point = new BMap.Point(p0, p1); //118.230272,33.482474
							_that.arrPois.splice(1, 1, point);

						} else if (sure == 1) { //出发地
							_that.searchReuslt = rs;
							let p0 = rs.point.lng;
							let p1 = rs.point.lat;
							// var checksum = makerArry[i].checksum;
							let point = new BMap.Point(p0, p1); //118.230272,33.482474
							_that.arrPois.splice(0, 1, point);;
						}


						map.centerAndZoom(pp, 11);
						map.addOverlay(new BMap.Marker(pp)); //添加标注
						setTimeout(() => {
							_that.searchFlag = false;
						}, 1000)

					}
					let local = new BMap.LocalSearch(map, { //智能搜索
						onSearchComplete: myFun
					});
					local.search(myValue);

				}

			},

			getCarInfoByNum(car_num) {

				this.$axios.get('/api/info/carInfoByNum', {
						params: {
							id: car_num
						}
					})
					.then(data => {
						if (data.status == 200) {


							this.nowLoc.lat = this.car.cur_loc_lat;
							this.nowLoc.lon = this.car.cur_loc_lon;
							console.log(this.nowLoc.lon + '---' + this.nowLoc.lat)
							let point = new BMap.Point(this.nowLoc.lon, this.nowLoc.lat)
							console.log(point)
						}
					})
					.catch(err => {
						console.log(err)
					})
			},



		},

	}
</script>

<style scoped lang="less">
	/* 放大缩小地图控件 */
	.BMap_stdMpZoom {
		margin-top: 50px;
	}

	#map {

		position: relative;
		width: 100%;
		height: 615 px;

		#header {
			width: 100%;
			height: 50px;
			position: fixed;
			top: 3px;
			z-index: 12;
			background-color: rgba(0, 245, 250, 0.7);
			border-radius: 5px 5px 10px 10px;

			#r-result {
				position: relative;
				width: 100%;

				.search-position(@l) {
					position: absolute;
					top: 15px;
					left: @l;
					width: 350px;
					color: #000;
				}

				#chufa {
					.search-position(150px);
				}

				#mudi {
					.search-position(550px);
				}

				.btn-class {
					color: #fff;
					position: absolute;
					top: 3px;
					right: 40px;
				}
			}


			.div_input::after {
				content: '';
				height: 0;
				display: block;
				clear: both;
				visibility: hidden;
			}

			.div_input {
				width: 100%;
				height: 52px;
				float: left;
				text-align: left;

			}

			#dingwei {
				padding: 0
			}

			.dingwei-img {
				width: 16px;

				height: 16px;

			}
		}


		.div_map {
			width: 100%;
			height: 600px;
			top: 80px;

			position: relative;
			overflow: hidden;

			#allmap {
				position: absolute;

				height: 600px;
				top: 0;

				width: 100%;
			}
		}

	}
</style>
